import React, { Component } from "react"
import { Form, Input, Button, Card, Checkbox, message } from "antd"
import "./index.scss"
import logo from "assets/logo.png"
import { login } from "api/user"
// 导入token
import { setToken } from "utils/storage"
export default class Login extends Component {
  state = {
    loading: false
  }
  render() {
    return (
      <div className="login">
        <Card className="login-container">
          <img className="login-logo" src={logo} alt="" />
          {/* 表单 */}
          <Form
            size="large"
            validateTrigger={["onChange", "onBlur"]}
            initialValues={{ agree: true, mobile: "13911111111", code: "246810" }}
            onFinish={this.onFinish}>
            <Form.Item
              name="mobile"
              rules={[
                {
                  pattern: /^1[3-9]\d{9}$/,
                  message: "手机号码格式不对"
                },
                { required: true, message: "请输入手机号" }
              ]}>
              <Input placeholder="请输入您的手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                {
                  pattern: /^\d{6}$/,
                  message: "验证码错误"
                },
                { required: true, message: "请输入验证码" }
              ]}>
              <Input placeholder="请输入验证码"></Input>
            </Form.Item>

            <Form.Item
              name="agree"
              valuePropName="checked"
              rules={[
                {
                  validator: this.validator
                }
              ]}>
              <Checkbox>我已阅读并同意[用户协议]和[隐私条款]</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button type="primary" block htmlType="submit" loading={this.state.loading}>
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }

  // 提交表单
  onFinish = async ({ mobile, code }) => {
    // loading加载状态
    this.setState({
      loading: true
    })
    try {
      const res = await login(mobile, code)
      // 存储token
      // localStorage.setItem("geekToken", res.data.token)
      setToken(res.data.token)
      // 跳转到首页  判断location.state中是否有值
      // console.log(this.props)
      // 判断location.state中是否有值 回跳
      const { state } = this.props.location
      if (state) {
        this.props.history.push(state.from)
      } else {
        this.props.history.push("/home")
      }
      message.success("登录成功", 1)
    } catch (err) {
      message.warning(err.response.message, 1, () => {
        this.setState({
          loading: false
        })
      })
    }
  }
  // 自定义校验规则
  validator = (rules, value) =>
    value ? Promise.resolve() : Promise.reject(new Error("请阅读协议并勾选协议"))
}
